package java;

public class Question29 {
    public static void main(String[] args) {
        System.out.println(divide(Integer.MIN_VALUE,-1));
        System.out.println(myDivide(Integer.MIN_VALUE,-1));
    }

    private static int myDivide(int dividend, int divisor) {
        boolean sign = !(dividend > 0) ^ (divisor > 0);
        if (dividend > 0) {
            dividend = -dividend;
        }
        if (divisor > 0){
            divisor = -divisor;
        }
        int res = 0;
        while (dividend <= divisor){
            int resTemp = -1;
            int dividedTemp = dividend;
            int divisorTemp = divisor;
            while (dividedTemp <= (divisorTemp << 1)){
                if(divisorTemp <= (Integer.MIN_VALUE >> 1)){
                    break;
                }
                resTemp = resTemp << 1;
                divisorTemp = divisorTemp << 1;
            }
            res += resTemp;
            dividend = dividend - divisorTemp;
        }

        if (sign){
            if (res == Integer.MIN_VALUE){
                return Integer.MAX_VALUE;
            }
            return -res;
        }
        return +res;
    }

    public static int divide(int dividend, int divisor) {
        boolean sign = (dividend > 0) ^ (divisor > 0);
        int result = 0;
        if(dividend>0) {
            dividend = -dividend;
        }
        if(divisor>0) divisor = -divisor;
        while(dividend <= divisor) {
            int temp_result = -1;
            int temp_divisor = divisor;
            while(dividend <= (temp_divisor << 1)) {
                if(temp_divisor <= (Integer.MIN_VALUE >> 1)){
                    break;
                }
                temp_result = temp_result << 1;
                temp_divisor = temp_divisor << 1;
            }
            dividend = dividend - temp_divisor;
            result += temp_result;
        }
        if(!sign) {
            if(result <= Integer.MIN_VALUE) return Integer.MAX_VALUE;
            result = - result;
        }
        return result;
    }
}
